<script setup>
import httpInstance from "@/axios/index";
import {useUserStore} from '@/stores/user.js'
import {onMounted, ref} from "vue";
import {EditPen, Plus} from "@element-plus/icons-vue";
import dayjs from "dayjs";
import {ElMessage} from "element-plus";
import qs from "qs";
import { useRouter } from "vue-router";
const Router = useRouter()

const userStore = useUserStore()
const loginTime = ref("")
const loginIp = ref("")
//分页信息
const page = ref({
  pageNo: 1,
  pageSize: 5,
  pageTotal: 0
})
const getLoginLog = () => {
  httpInstance.get('/loginLog/currentSysUserLoginLog?pageNo=' + page.value.pageNo + '&pageSize=' + page.value.pageSize)
      .then(responseData => {
        userStore.loginLog = responseData.data.records
        if (loginTime.value.trim().length === 0) {
          loginTime.value = dayjs(userStore.loginLog[0].loginTime).format('YYYY-MM-DD HH:mm:ss')
          loginIp.value = userStore.loginLog[0].loginIp
        }
        page.value.pageNo = responseData.data.current
        page.value.pageTotal = responseData.data.total
      })
      .catch(error => {

      })
}
onMounted(getLoginLog)

//获取当前角色信息
const getUserInfoById = () => {
  httpInstance.get('/auth/currentSysUserInfo')
      .then(responseData => {
        userStore.userInfo = responseData.data
        fromData.value.realName = userStore.userInfo.realName
        fromData.value.avatarUrl = userStore.userInfo.avatarUrl
      })
}

//抽屉
const updateType = ref("info")
const dialog = ref(false)
const loading = ref(false)
const fromData = ref({
  oldPassword: "",
  newPassword: "",
  rePassword: "",
  realName: "",
  avatarUrl: ""
})

const handleClose = (done) => {
  if (loading.value) {
    return
  }
  dialog.value = false
  fromData.value = {
    oldPassword: "",
    newPassword: "",
    rePassword: "",
    realName: "",
    avatarUrl: ""
  }
}
//数据操作
const onClick = () => {
  if (updateType.value === "info") {
    updateInfo()
  } else {
    updatePassword()
  }
}
//修改信息
const updateInfo = () => {
  httpInstance.put('/profile/modifyInfo', qs.stringify(fromData.value))
      .then(responseData => {
        if (responseData.code === 200) {
          ElMessage.success("修改成功")
          getUserInfoById()
          handleClose()
        } else {
          ElMessage.error("修改失败")
        }
      })
}

//注销功能
const logout = () => {
  httpInstance.get("/auth/logout")
      .then((responseData) => {
        console.log(responseData)
        if (responseData.code === 200) {
          localStorage.removeItem("Authorization");
          localStorage.removeItem("password")
          ElMessage.success(responseData.message)
          Router.push("/")
        }else{
          localStorage.removeItem("Authorization");
          Router.push("/")
        }
      })
      .catch((res) => {
        ElMessage.error(res.message)
      })
}

//修改密码
const updatePassword = () => {
  //验证
  if (fromData.value.oldPassword.trim().length === 0) {
    ElMessage.error("旧密码不能为空")
    return
  }
  if (fromData.value.newPassword.trim().length === 0) {
    ElMessage.error("新密码不能为空")
    return
  }
  if (fromData.value.rePassword.trim().length === 0) {
    ElMessage.error("确认密码不能为空")
    return
  }
  if (fromData.value.newPassword !== fromData.value.rePassword) {
    ElMessage.error("两次密码不一致")
    return
  }
  httpInstance.put('/profile/modifyPassword', qs.stringify(fromData.value))
      .then(responseData => {
        if (responseData.code === 200) {
          ElMessage.success("修改成功,3秒后自动跳转到登录页")
          setTimeout(() => {
            logout()
          }, 3000)
          handleClose()
        } else {
          ElMessage.error("修改失败")
        }
      })
}

//图片上传部分
// 文件上传URL，从axios的配置项中取到统一前缀
const uploadUrl = 'http://localhost:8080/api/file/upload'
const uploadHeader = ref({
  // 文件上传请求头，后端接口是需要验证是否登录的
  Authorization: localStorage.getItem("Authorization")
})

const handleAvatarSuccess = (res, file) => {
  // res：上传成功后服务器返回的数据
  fromData.value.avatarUrl = res.data.path;
}
const beforeAvatarUpload = (file) => {
  const isJPG = file.type === "image/jpeg" || file.type === "image/png";
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJPG) {
    ElMessage.error('上传头像图片只能是 JPG和PNG 格式');
  }
  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过 2MB');
  }
  return isJPG && isLt2M;
}
</script>

<template>
  <el-row>
    <el-drawer
        v-model="dialog"
        title="数据操作"
        :before-close="handleClose"
        class="demo-drawer"
    >
      <div class="demo-drawer__content">
        <el-form
            v-if="updateType === 'info'"
            label-position="top"
            label-width="auto"
            :model="fromData"
            style="max-width: 600px"
        >
          <el-form-item>
            <el-input type="text" disabled value="点击下方按钮上传头像">
              <template slot="prepend">账户头像</template>
            </el-input>
            <el-upload
                class="avatar-uploader"
                :action="uploadUrl"
                :headers="uploadHeader"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
            >
              <img v-if="fromData.avatarUrl" :src="fromData.avatarUrl" class="avatar" alt=""/>
              <el-icon v-else class="avatar-uploader-icon">
                <Plus/>
              </el-icon>
            </el-upload>
          </el-form-item>
          <el-form-item>
            <el-input v-model="fromData.realName">
              <template #prepend>真实姓名</template>
            </el-input>
          </el-form-item>
        </el-form>
        <el-form
            v-if="updateType === 'password'"
            label-position="top"
            label-width="auto"
            :model="fromData"
            style="max-width: 600px"
        >
          <el-form-item>
            <el-input type="password" style="margin-bottom: 10px" v-model="fromData.oldPassword" placeholder="请输入旧密码">
              <template #prepend>旧密码</template>
            </el-input>
            <el-input  type="password"  style="margin-bottom: 10px" v-model="fromData.newPassword" placeholder="请输入新密码">
              <template #prepend>新密码</template>
            </el-input>
            <el-input  type="password"  style="margin-bottom: 10px" v-model="fromData.rePassword" placeholder="请再次输入新密码">
              <template #prepend>再次输入新密码</template>
            </el-input>
          </el-form-item>
        </el-form>
        <div class="demo-drawer__footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" :loading="loading" @click="onClick">
            {{ loading ? '提交中...' : '提交' }}
          </el-button>
        </div>
      </div>
    </el-drawer>
    <el-col :span="6" style="padding-right: 20px">
      <el-card style="min-width: 100%">
        <div slot="header" class="info-header">
          <el-image style="width: 60px; height: 60px" :src="userStore.userInfo.avatarUrl" fit="fill"/>
          <p>{{ userStore.userInfo.realName }}</p>
          <el-tag size="small">{{ userStore.userInfo.sysRole && userStore.userInfo.sysRole.roleName }}</el-tag>
        </div>
        <div class="text item">
          <p><span>账户账号</span>{{ userStore.userInfo.account }}</p>
          <p><span>真实姓名</span>{{ userStore.userInfo.realName }}</p>
          <p><span>最后登录时间</span>{{ loginTime }}</p>
          <p><span>最后登录IP</span>{{ loginIp }}</p>
        </div>
        <div slot="footer" class="info-footer">
          <el-button size="small" color="#F2F3F5" @click="getUserInfoById();dialog = true;updateType='info'"><el-icon><EditPen /></el-icon>修改基本信息</el-button>
          <el-button size="small" color="#F2F3F5" @click="dialog = true;updateType='password'"><el-icon><EditPen /></el-icon>修改账户密码</el-button>
        </div>
      </el-card>
    </el-col>
    <el-col :span="18">
      <el-card>
        <div class="text item">
          <el-table :data="userStore.loginLog" height="360px" style="width: 100%;min-height: 340px" border>
            <el-table-column prop="id" label="排序" width="100" header-align="center" align="center"/>
            <el-table-column prop="loginArea" label="会话IP信息" header-align="center" align="center"/>
            <el-table-column prop="loginIp" label="会话IP" header-align="center" align="center"/>
            <el-table-column label="登录时间" header-align="center" align="center">
              <template #default="scope">
                {{ dayjs(scope.row.loginTime).format('YYYY-MM-DD HH:mm:ss') }}
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div slot="footer" class="card-footer">
          <el-pagination
              v-model:current-page="page.pageNo"
              v-model:page-size="page.pageSize"
              :page-sizes="[5, 10, 15, 20]"
              background
              layout="sizes, prev, pager, next"
              :total="page.pageTotal"
              @size-change="getLoginLog"
              @current-change="getLoginLog"
          />
        </div>
      </el-card>
    </el-col>
  </el-row>
</template>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}


.card-footer {
  display: flex;
  justify-content: flex-end;
}
.text{
  display: flex;
  font-size: 14px;
  flex-direction: column;
}
.text p{
  margin-bottom: 15px;
}
.text p span{
  display: inline-block;
  width: 37%;
  font-weight: lighter;
}

.el-image__inner {
  width: 60px;
  height: 60px;
  border-radius: 50%
}

.info-header {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin: 25px 0;
}

.info-header p {
  margin-top: 10px;
  margin-bottom: 10px;
  font-weight: lighter;
}

.info-footer {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  font-size: 14px;
  margin: 25px 0;
}
</style>